package com.cskaoyan.service;


import com.cskaoyan.bean.admin.admin.vo.AdminListVo;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.util.Constant;
import com.cskaoyan.util.Md5Util;
import com.cskaoyan.util.StringUtil;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lwq
 * @since 2022/11/19 17:13
 */
@Service
@Transactional
public class AdminServiceImpl implements AdminService {
    @Autowired
    MarketAdminMapper marketAdminMapper;
    @Autowired
    MarketStorageMapper marketStorageMapper;
    @Autowired
    MarketRoleMapper marketRoleMapper;

    /**
     * 查询管理员
     *
     * @param basePageInfo
     * @param username
     * @return com.cskaoyan.bean.common.CommonData
     * @author lwq
     * @since 2022/11/20 21:52
     */
    @Override
    public CommonData list(BasePageInfo basePageInfo, String username) {
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        if (!StringUtil.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(marketAdminExample);
        List<AdminListVo> adminListVos = new ArrayList<>();
        for (MarketAdmin marketAdmin : marketAdmins) {
            AdminListVo adminListVo = new AdminListVo(marketAdmin.getId(), marketAdmin.getUsername(), marketAdmin.getAvatar(), marketAdmin.getRoleIds());
            adminListVos.add(adminListVo);
        }
        PageInfo<AdminListVo> pageInfo = new PageInfo<>(adminListVos);
        return CommonData.data(pageInfo);
    }

    /**
     * 添加管理员
     *
     * @param marketAdmin
     * @return com.cskaoyan.bean.po.MarketAdmin
     * @author lwq
     * @since 2022/11/20 21:52
     */
    @Override
    public MarketAdmin create(MarketAdmin marketAdmin) {
        if (AdminsIsExists(marketAdmin)) {
            // 管理员存在
            return null;
        }
        // TODO 密码加密
        String md5 = Md5Util.getMd5(marketAdmin.getPassword(), "crazy");
        marketAdmin.setPassword(md5);
        marketAdmin.setAddTime(new Date());
        marketAdmin.setUpdateTime(new Date());
        int affectedRows = marketAdminMapper.insertSelective(marketAdmin);
        updateRoleEnable(marketAdmin);
        if (affectedRows == 1) {
            return marketAdmin;
        }
        return null;
    }

    private void updateRoleEnable(MarketAdmin marketAdmin) {
        MarketRole marketRole = new MarketRole();
        marketRole.setEnabled(true);
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        Integer[] roleIds = marketAdmin.getRoleIds();
        if (roleIds != null && roleIds.length != 0) {
            List<Integer> roleIdList = new ArrayList<>();
            for (Integer roleId : roleIds) {
                roleIdList.add(roleId);
            }
            criteria.andIdIn(roleIdList);
            marketRoleMapper.updateByExampleSelective(marketRole, marketRoleExample);
        }
    }

    /**
     * 判断管理员是否存在
     *
     * @param marketAdmin
     * @return java.util.List<com.cskaoyan.bean.po.MarketAdmin>
     * @author lwq
     * @since 2022/11/22 14:35
     */
    private boolean AdminsIsExists(MarketAdmin marketAdmin) {
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        if (!StringUtil.isEmpty(marketAdmin.getUsername())) {
            criteria.andUsernameEqualTo(marketAdmin.getUsername());
        }
        criteria.andDeletedEqualTo(false);
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(marketAdminExample);
        return (marketAdmins != null && marketAdmins.size() != 0);
    }

    /**
     * 修改管理员
     *
     * @param marketAdmin
     * @return com.cskaoyan.bean.po.MarketAdmin
     * @author lwq
     * @since 2022/11/20 21:53
     */
    @Override
    public MarketAdmin update(MarketAdmin marketAdmin) {
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdNotEqualTo(marketAdmin.getId());
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(marketAdminExample);
        for (MarketAdmin admin : marketAdmins) {
            if (marketAdmin.getUsername().equals(admin.getUsername())) {
                throw new DuplicateKeyException("管理员名称重复");
            }
        }
        marketAdmin.setUpdateTime(new Date());
        // TODO 密码加密
        String md5 = Md5Util.getMd5(marketAdmin.getPassword(), "crazy");
        marketAdmin.setPassword(md5);
        int affectedRows = marketAdminMapper.updateByPrimaryKeySelective(marketAdmin);
        updateRoleEnable(marketAdmin);
        if (affectedRows == 1) {
            return marketAdmin;
        }
        return null;
    }

    /**
     * 逻辑删除管理员
     *
     * @param marketAdmin
     * @return int
     * @author lwq
     * @since 2022/11/20 22:19
     */
    @Override
    public int delete(MarketAdmin marketAdmin) {
        String avatar = marketAdmin.getAvatar();
        String key = avatar.replace(Constant.imgUrl, "");
        MarketStorageExample marketStorageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = marketStorageExample.createCriteria();
        if (!StringUtil.isEmpty(key)) {
            criteria.andKeyEqualTo(key);
        }
        // 逻辑删除storage
        int affectRows;
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setDeleted(true);
        affectRows = marketStorageMapper.updateByExampleSelective(marketStorage, marketStorageExample);
        // 逻辑删除admin
        marketAdmin.setDeleted(true);
        affectRows = marketAdminMapper.updateByPrimaryKeySelective(marketAdmin);
        return affectRows;
    }
}
